﻿using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;

namespace Cheng.UI
{
    public class UGuiGroupHelper : UIGroupHelperBase
    {
        public const int DepthFactor = 1000;

        private int m_Depth = 0;
        private Canvas m_CachedCanvas = null;

        private Transform Mask;
        /// <summary>
        /// 设置界面组深度。
        /// </summary>
        /// <param name="depth">界面组深度。</param>
        public override void SetDepth(int depth)
        {
            m_Depth = depth;
            m_CachedCanvas.overrideSorting = true;
            m_CachedCanvas.sortingOrder = DepthFactor * depth;
        }

        private void Awake()
        {
            m_CachedCanvas = gameObject.GetOrAddComponent<Canvas>();
            gameObject.GetOrAddComponent<GraphicRaycaster>();
        }

        private void Start()
        {
            m_CachedCanvas.overrideSorting = true;
            m_CachedCanvas.sortingOrder = DepthFactor * m_Depth;

            RectTransform transform = GetComponent<RectTransform>();
            transform.anchorMin = Vector2.zero;
            transform.anchorMax = Vector2.one;
            transform.anchoredPosition = Vector2.zero;
            transform.sizeDelta = Vector2.zero;
        }

        /// <summary>
        /// 设置遮罩
        /// </summary>
        /// <param name="show"></param>
        public void SetMask(string name,bool show=true)
        {
            if(Mask==null)
            {
                Mask = transform.GetChildByName("Mask");
            }
            Transform uiForm = null;
            //判断这个界面是否打开过
            if (show)
            {
                //检测是否是第二次打开
                uiForm = transform.GetChildByName(name.Contains("Clone") ? name : name + "(Clone)");
            }
            else
            {
                //检测是否存在其他界面
                for (int i = 0; i < transform.childCount; i++)
                {
                    if(transform.GetChild(i).gameObject.activeSelf && transform.GetChild(i).gameObject.name!="Mask")
                    {
                        uiForm = transform.GetChild(i);
                        break;
                    }
                }
            }
            
            int index= uiForm==null?-1: uiForm.GetSiblingIndex();
            Mask.SetSiblingIndex(show?(index==-1?transform.childCount: Mathf.Max(0, index - 1)) : (index == -1 ? transform.childCount-3: Mathf.Max(0, index - 1)));
            Mask?.gameObject.SetActive((index != -1&& !show) ?true:show);
        }
    }
}